<template>
  <div class="create-note-container">
    <div class="page-header">
      <h1 class="page-title">写笔记</h1>
      <el-button @click="goBack">返回</el-button>
    </div>

    <el-form 
      ref="formRef" 
      :model="noteForm" 
      :rules="rules" 
      label-width="80px"
      class="note-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input 
          v-model="noteForm.title" 
          placeholder="请输入笔记标题（5-50字）"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <el-input 
          v-model="noteForm.content" 
          type="textarea" 
          :rows="12"
          placeholder="请输入笔记内容（10-5000字）"
          maxlength="5000"
          show-word-limit
        ></el-input>
      </el-form-item>

      <el-form-item label="相关课程" prop="courseId">
        <el-select
          v-model="noteForm.courseId"
          filterable
          placeholder="请选择相关课程（可选）"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="course in courseOptions"
            :key="course.id"
            :label="course.title"
            :value="course.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="noteForm.tags"
          multiple
          filterable
          allow-create
          default-first-option
          placeholder="请选择或创建标签（最多5个）"
          style="width: 100%"
          :max-collapse-tags="3"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="是否公开" prop="isPublic">
        <el-switch
          v-model="noteForm.isPublic"
          active-text="公开"
          inactive-text="私密"
        ></el-switch>
        <div class="tip-text">公开的笔记将显示在社区中，私密笔记仅自己可见</div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm" :loading="submitting">发布笔记</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

const store = useStore();
const router = useRouter();
const formRef = ref(null);
const submitting = ref(false);

// 常用标签
const commonTags = [
  '数学', '物理', '化学', '生物', '语文', '英语', '历史', '地理', '政治',
  '高考', '中考', '考研', '学习方法', '学习笔记', '知识点总结', '公式推导'
];

// 课程选项
const courseOptions = computed(() => {
  // 从store中获取课程列表
  const courseDetails = store.state.course.courseDetails;
  return Object.values(courseDetails || {});
});

// 表单数据
const noteForm = reactive({
  title: '',
  content: '',
  courseId: '',
  tags: [],
  isPublic: true
});

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入笔记标题', trigger: 'blur' },
    { min: 5, max: 50, message: '标题长度应在5-50个字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入笔记内容', trigger: 'blur' },
    { min: 10, max: 5000, message: '内容长度应在10-5000个字符之间', trigger: 'blur' }
  ],
  tags: [
    { required: true, message: '请至少选择一个标签', trigger: 'change' },
    { 
      validator: (rule, value, callback) => {
        if (value.length > 5) {
          callback(new Error('最多选择5个标签'));
        } else {
          callback();
        }
      }, 
      trigger: 'change' 
    }
  ]
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      submitting.value = true;
      try {
        // 调用store的action创建笔记
        const result = await store.dispatch('community/createNote', {
          title: noteForm.title,
          content: noteForm.content,
          courseId: noteForm.courseId || null,
          tags: noteForm.tags,
          isPublic: noteForm.isPublic
        });
        
        ElMessage.success('笔记发布成功');
        // 跳转到新创建的笔记详情页
        router.push(`/community/note/${result.id}`);
      } catch (error) {
        ElMessage.error('发布失败，请稍后重试');
        console.error(error);
      } finally {
        submitting.value = false;
      }
    } else {
      console.log('表单验证失败', fields);
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};
</script>

<style lang="scss" scoped>
.create-note-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .page-title {
    font-size: 24px;
    margin: 0;
  }
}

.note-form {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  .tip-text {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }
}
</style> 